import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
// 路由列表;
const routes = [{
  name: '/',
  path: '/',
  redirect: '/login'
},
{
  name: 'login',
  path: '/login',
  component: () => import('@/views/Login.vue')
},
{
  name: 'index',
  path: '/index',
  component: () => import('@/views/DashBoard.vue'),
}]
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
  // 处理滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0
    }
  }
})
// 路由守卫
router.beforeEach((to, from, next) => {
  nprogress.start();
  let { isLogin } = storeToRefs(useUserStore());
  if (isLogin.value) {
    if (to.name === 'login') {
      next('/index');
      nprogress.done()
    } else {
      next();
      nprogress.done()
    }
  } else {
    if (to.name === 'index') {
      next('/');
      nprogress.done()
    } else {
      next();
      nprogress.done()
    }
  }
})
router.afterEach((to, from) => {
  // 保底关进度条  
  nprogress.done()
})

export default router
